<?php
/**
 * Created by PhpStorm.
 * User: macmini
 * Date: 2018/3/1
 * Time: 上午11:17
 */

namespace app\api\controller;

use app\common\controller\Api;
use think\Cache;
use think\captcha\Captcha;
use think\Cookie;

class Index extends Api 
{
    public function get_captcha($id)
    {
        $config =    [
            // 验证码字体大小
            'fontSize'    =>    30,
            // 验证码位数
            'length'      =>    4,
            // 关闭验证码杂点
            'useNoise'    =>    false,
            'useCurve' => false,
        ];
        session_start();
        $s_id = session_id();
        $model = db('code');
        $info = $model->where('id', $id)->find();
        if ($info) {
            $model->where('id', $id)->update(['session_id'=>$s_id]);
        } else {
            $model->insert(['id' => $id, 'session_id' => $s_id]);
        }
        $captcha = new Captcha($config);
        return $captcha->entry($id);
    }

    // 检测输入的验证码是否正确，$code为用户输入的验证码字符串，$id多个验证码标识
    function check_verify($code, $id = '')
    {

        $captcha = new Captcha();
        return $captcha->check($code, $id);
    }

    public function cates()
    {
        $info = db('Cates')->select();
        $res = db('Cates')->where('pid', 0)->select();
        foreach ($res as &$v) {
            foreach ($info as $vo) {
                if ($vo['pid'] == $v['id']) {
                    $v['next'][] = $vo;
                }
            }
        }
        return $this->responseSend(0, $res, 200);
    }

    public function goods()
    {
        $cid = request()->get('cid', 0);
        $where = [];
        if ($cid) {
            $where['cid'] = $cid;
        }
        $res = model('Goods')->where($where)->paginate(10,false,[
            'query' => request()->get()
        ]);
        return $this->responseSend(0, $res, 200);
    }

    public function format()
    {
        $data = request()->post();
        $user_id = $this->getUserId($data['token']);
        if ($user_id == 300) {
            return $this->responseSend(0, '', 300);
        }
        $res = db('sku')->where('goods_id', $data['goods_id'])->select();
        foreach ($res as &$v) {
            $info = db('SkuItem')->where('sku_id', $v['id'])->select();
            $name = $v['name'];
            foreach ($info as $vo) {
                $r = db('items')->where('id', $vo['item_id'])->find();
                $name .= '+' . $r['name'];
            }
            $v['name'] = $name;
        }
        return $this->responseSend(0, $res, 200);
    }

    public function order()
    {
        $data = request()->post();
        $user_id = $this->getUserId($data['token']);
        if ($user_id == 300) {
            return $this->responseSend(0, '', 300);
        }

    }

    public function test()
    {
        echo cookie('1523095899703');
    }
}
